jQuery(document).ready(function() {
	var orgData = {};
	$.ajax({
		async : false,
		url : projectPath + "user/getCurrentUser.do",
		data : {},
		dataType : "json",
		success : function(data) {
			orgData = data;
			$('#orgSelect').val(orgData.orgname);
			$('#orgSelect').attr('data', orgData.orgcode);
		}
	});
	initTable();
	
	bindOrg2('orgSelect');
//	bindOrg("orgSelect","2","0","");
	
	App.setPage("notice"); // Set current page
	App.init(); // Initialise plugins and elements
										
	//时间范围
	$('#st').change(function(){
		if('' != $('#en').val()){
			if(Date.parse($('#st').val()) > Date.parse($('#en').val())){
				$('#en').val('');
			}
		}
		if('' == $('#st').val()){
			$('#en').removeAttr('min');
		} else {
			$('#en').attr('min', $('#st').val());
		}
	});
		

	// 发布时间
	$("#day").click(function() {
		if (this.checked) {
			$("#month").prop("checked", false);
			$("#week").prop("checked", false);
		}
	});
	
	$("#week").click(function() {
		if (this.checked) {
			$("#month").prop("checked", false);
			$("#day").prop("checked", false);
		}
	});
	
	$("#month").click(function() {
		if (this.checked) {
			$("#week").prop("checked", false);
			$("#day").prop("checked", false);
		}
	});

	// 根据选择给时间控件时间范围
	$("#day,#month,#week").click(function() {
		var fbtime = new Date();
		var year = fbtime.getFullYear();
		var month = fbtime.getMonth();
		var day = fbtime.getDate();
		var startDate = "";
		var endDate = "";
		var dayStr = "01";
		var monthStr = "01";
		if ($("#day").prop("checked")) {
			dayStr = day > 9 ? day : '0' + day;
			monthStr = (month + 1) > 9 ? (month + 1) : '0' + (month + 1);
			startDate = year + "-" + monthStr + "-"+ dayStr;
			endDate = year + "-" + monthStr + "-"+ dayStr;
		} else if ($("#week").prop("checked")) {
			var nowTime = fbtime.getTime();
			var day = fbtime.getDay();
			var oneDayLong = 24 * 60 * 60 * 1000;
			var MondayTime = nowTime - (day - 1)* oneDayLong;
			var SundayTime = nowTime + (7 - day)* oneDayLong;
			var monday = new Date(MondayTime);
			var sunday = new Date(SundayTime);
			
			monthStr = (monday.getMonth() + 1) > 9 ? (monday.getMonth() + 1) : '0' + (monday.getMonth() + 1);
			dayStr = monday.getDate() > 9 ? monday.getDate() : '0' + monday.getDate();
			startDate = monday.getFullYear() + "-"+ monthStr + "-"+ dayStr;
			
			dayStr = (monday.getDate() + 6) > 9 ? (monday.getDate() + 6) : '0' + (monday.getDate() + 6);
			endDate = monday.getFullYear() + "-"+ monthStr + "-"+ (monday.getDate() + 6);
			
		} else if ($("#month").prop("checked")) {
			monthStr = (month + 1) > 9 ? (month + 1) : '0' + (month + 1);
			startDate = year + "-" + monthStr + "-01";
			endDate = year + "-" + (month + 2) + "-01";
			
			var end = new Date(endDate);
			var preDate = new Date(end.getTime() - 24 * 60 * 60 * 1000);
			
			dayStr = preDate.getDate() > 9 ? preDate.getDate() : '0' + preDate.getDate();
			monthStr = (preDate.getMonth() + 1) > 9 ? (preDate.getMonth() + 1) : '0' + (preDate.getMonth() + 1);
			endDate = preDate.getFullYear() + "-"+ monthStr + "-"+ dayStr;
		}
		
		if (startDate != "") {
			$('#st').val(startDate);
			$('#en').val(endDate);
			$('#st').attr('min', startDate);
			$('#st').attr('max', endDate);
			$('#en').attr('min', startDate);
			$('#en').attr('max', endDate);
		} else {
			$('#st').val('');
			$('#en').val('');
			$('#st').removeAttr('min');
			$('#st').removeAttr('max');
			$('#en').removeAttr('min');
			$('#en').removeAttr('max');
		}
	});

	// 列表查询事件
	$('#search').click(function() {
		$('#notice').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
	});

	// 新增公告
	$('#addNotice').click(function() {		
		setModalSize();   	
    	$('#ifModal').attr("src", "add.html");    	
		$('#modalTile').html("公告新增");
		$("#modalNotice").modal('show');
	});

	// 批量删除
	$('#batchDelete').click(
		function() {
			var data = $('#notice').bootstrapTable('getSelections');
			if(data.length <= 0){
				window.wxc.xcConfirm('请勾选要<strong>批量删除</strong>的公告数据', window.wxc.xcConfirm.typeEnum.info);
				return;
			}
			var noticecodes = "";
			var noticetitle = "";
			for (var i = 0; i < data.length; i++) {
				noticecodes += data[i].noticeId+ ",";
				noticetitle += data[i].title + ",";
			}
			noticecodes = noticecodes.substring(0,noticecodes.length - 1);
			noticetitle = noticetitle.substring(0,noticetitle.length - 1);
			window.wxc.xcConfirm('是否<strong>批量删除</strong>公告数据?<br /><span style="color:red;">['+ noticetitle+ ']</span>', window.wxc.xcConfirm.typeEnum.confirm,{
				onOk:function(v){
					$.ajax({
						url : basePath()+ 'notice/batchDelete.do',
						data : {
							"noticecodes" : noticecodes
						},
						ataType : "json",
						success : function(data) {																
							$('#notice').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
						}
					});
				}
			});
		});

		//刷新数据事件
		$('#refresh').click(function(){
			$('#notice').bootstrapTable(('refresh'));
		});

		//保存数据事件
		$('#save').click(function(){
			$("#ifModal")[0].contentWindow.save();
		});
					

		// 清空表单数据事件
		$("#modalNotice").on("hidden.bs.modal", function() {
			$(this).find("[type='text']").val('');
			$(this).find("[name='file']").val('');
			$(this).find("[name='noticeId']").val('');
			$(this).find("[name='contents']").val('');
			$(this).find("[name='orgCode']").val('');
			$("#sxDate").hide();
			$("#sx").html("置顶失效时间：");
		});
	});

// 初始化字典列表
function initTable() {
	$('#notice').bootstrapTable(
			{
				method : 'post',
				url : basePath() + 'notice/list.do',
				pagination : true, // 分页
				dataType : "json",
				contentType : "application/json",
				pageList : [ 10, 20, 50, 100 ], // 可供选择的每页的行数（*）
				striped : true, // 是否显示行间隔色
				sidePagination : "server",
				//查询参数,每次调用是会带上这个参数，可自定义
				queryParams : function(params) {
					var startDate = $("#st").val() + " 00:00:00";
					var endDate = $("#en").val() + " 23:59:59";

					if (startDate == " 00:00:00") {
						startDate = null;
					}
					if (endDate == " 23:59:59") {
						endDate = null;
					}	
					return {
						orgCode : $("#orgSelect").attr("data"),
						startDate : startDate,
						endDate : endDate,
						title : $('#title').val(),
						pageNum : params.offset / params.limit + 1,
						pageSize : params.limit
					};
				},
				columns : [
						{
							field : 'checked',
							checkbox : true
						},
						{
							field : 'number',
							title : '序号',
							align : 'center',
							width : '80px',
							formatter : function(value, row, index) {
								// return index + 1;
								var page = $('#notice').bootstrapTable("getPage");
								return page.pageSize * (page.pageNumber - 1) + index + 1;
							}
						}, {
							field : 'noticeId',
							visible : false
						}, {
							field : 'symbol',
							visible : false
						}, {
							field : 'contents',
							visible : false					
						}, {
							field : 'orgCode',
							visible : false
						}, {
							field : 'top',
							visible : false
						}, {
							field : 'fileId',
							visible : false
						}, {
							field : 'failDate',
							visible : false
						}, {
							field : 'theme',
							visible : false
						}, {
							field : 'label',
							visible : false
						}, {
							field : 'evaluation',
							visible : false
						}, {
							field : 'title',
							title : '通知公告标题',
							formatter : function (value, row, index) {
								var time = new Date();
								var sx = row.failDate;
								var sxtime = new Date(sx);
								if(sxtime != null){
									if(row.top==1 && time<sxtime){
										return '<button class="btn btn-xs btn-danger disabled" style="font-size: 10px;padding:0px 5px;margin-right: 4px;opacity: 1;">置顶</button><span style="color:red;">'+value+'</span>';
									}
								}
								return '<span>'+value+'</span>';
							}
						}, {
							field : 'orgName',
							title : '发布机构'
						}, {
							field : 'range',
							title : '发布范围',
							visible : false
						}, {
							field : 'publishTime',
							title : '发布日期'
						}, {
							field : 'asofDate',
							title : '有效期止'
						}, {
							field : 'operate',
							title : '操作',
							align : 'center',
							width : '300px',
							events : operateEvents,
							formatter : operateFormatter
						}]
			});
}

function operateFormatter(value, row, index) {
	return [
			'<button type="button" class="Edit btn btn-warning  btn-sm" style="margin-right:10px;"><span class="glyphicon glyphicon-edit"></span>编辑</button>',
			'<button type="button" class="Delete btn btn-danger  btn-sm" style="margin-right:10px;"><span class="glyphicon glyphicon-minus"></span>删除</button>' ]
			.join('');
}

window.operateEvents = {
	'click .Edit' : function(e, value, row, index) {
		var noticeId = row.noticeId;		
		setModalSize();   	
    	$('#ifModal').attr("src", "edit.html?noticeId=" + noticeId);  	
		$('#modalTile').html("公告修改");		
		$("#modalNotice").modal('show');

	},
	'click .Delete' : function(e, value, row, index) {
		var noticeId = row.noticeId;
		var title = row.title;
		window.wxc.xcConfirm('是否<strong>删除</strong>公告数据?<br /><span style="color:red;">['+ title + ']</span>', window.wxc.xcConfirm.typeEnum.confirm,{
			onOk:function(v){
				$.ajax({
					url : basePath() + 'notice/delete.do',
					data : {
						"noticeId" : noticeId
					},
					dataType : "json",
					success : function(data) {
						if (data.result == 1) {
							$('#notice').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
						}
					}
				});
			}
		});
	}
};


//获取一行数据
function getNoticeDataByNoticeId(noticeId){
	if(noticeId=="addNotice"){
		return null
	}else{
		var datas = $('#notice').bootstrapTable('getData');  	
		for(var i = 0; i<datas.length; i++){
			var data = datas[i];
			var lineNoticeId = data.noticeId;
			if(noticeId == lineNoticeId){
				return data;
			}
		}	
	}	
}